﻿using DataTurnClient.ViewModel;
using Splat;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataTurnClient.Server
{
    public class LogService
    {
        public LogService()
        {
        }
        /// <summary>
        /// 写入本地txt日志
        /// </summary>
        /// <param name="txt"></param>
        public void WriterText(string txtName, string txt)
        {
            var service = Locator.Current.GetService<MainTurnViewModel>();
            try
            {
                string path = @"log\";
                string readme = txtName + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
                string txtpath = path + "/" + readme;//文件存放路径
                DirectoryInfo directoryInfo = new DirectoryInfo(path);
                if (!directoryInfo.Exists)  //判断 文件夹是否存在
                {
                    directoryInfo.Create();
                }
                if (!File.Exists(txtpath))
                {
                    File.Create(txtpath).Close();//判断文件是否存在，创建txt文件后需要close，否则会出现文件占用情况
                }
                StreamWriter sw = new StreamWriter(txtpath, true, System.Text.Encoding.Default);//第一个参数代表路径，第二个参数表示文件是否覆盖还是在原有文件基础上添加，第三个参数代表编码格式
                sw.WriteLine(txt);//写入txt文件
                sw.Flush();
                sw.Close();
            }
            catch (Exception ex)
            {
                LogRead read = new LogRead();
                read.ModelName = "WriterText";
                read.ModelContent = $"   文件写入错误：   {ex.Message}";
                service.AddLogCommand.Execute(read).Subscribe();
            }
        }
    }
}
